package cn.yhr.summerboot.context;

import cn.yhr.summerboot.context.annon.Bean;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Tittle AutowiredAnnotationProcessor
 * @Description
 * @Author yhr
 * @Date 2018/11/27 10:11
 * @Version 1.0
 */
public class BeanAnnotationProcessor {
    private IocApplication ioc=IocApplication.getApplication();

    public void findBeanAnnoInClasses() throws InvocationTargetException, IllegalAccessException {
        //得到Ioc容器
        Collection<Object> applications = ioc.getApplications();
        Map<String, Object> beanMap = new HashMap<>();
        //得到迭代器
        Iterator<Object> iterator = applications.iterator();
        while (iterator.hasNext()){
            //得到每个bean
            Object application = iterator.next();
            Class<?> clazz = application.getClass();
            //得到对象类的所有属性
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                Bean bean = method.getAnnotation(Bean.class);
                //判断这个属性是否加了@Bean注解的
                if (bean != null) {
                    Object invoke = method.invoke(application);
                    if (bean.key() != null && bean.key().length > 0) {
                        String[] keys = bean.key();
                        for (String key : keys) {
                            beanMap.put(key, invoke);
                        }
                    } else {
                        beanMap.put(method.getName(), invoke);
                    }
                }
            }
        }
        ioc.putAll(beanMap);
    }

}
